package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.vo.LoginSuccessVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author 10574
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-12-14 09:25:25
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    StringRedisTemplate redisTemplate;


    @Override
    public LoginSuccessVo login(UserInfo userInfo) {
        //非空校验
        if(userInfo.getLoginName()==null||userInfo.getPasswd()==null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR_NULL);
        }
        LoginSuccessVo successVo = new LoginSuccessVo();
        UserInfo info = lambdaQuery().eq(UserInfo::getLoginName, userInfo.getLoginName()).one();
        if(info==null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR_USER);
        }
        if (MD5.encrypt(userInfo.getPasswd()).equals(info.getPasswd())){
            //校验成功，生成token
            String token=null;
            token = redisTemplate.opsForValue().get(RedisConst.USER_LOGIN_KEY_PREFIX + userInfo.getLoginName());
            if(StringUtils.isEmpty(token)){
                token = UUID.randomUUID().toString().replace("-","");
                //将生成的token存入redis
                redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token, JSON.toJSONString(info),1800, TimeUnit.SECONDS);
            }
            successVo.setToken(token);
            successVo.setNickName(info.getNickName());
            successVo.setUserId(info.getId());
            return successVo;
        }else {
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR_PWD);
        }
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
    }
}




